package cn.getech.data.development.controller;


import cn.getech.data.development.model.dto.*;
import cn.getech.data.development.model.qo.UploadVersionLogQO;
import cn.getech.data.development.model.vo.*;
import cn.getech.data.development.service.UploadVersionLogService;
import cn.getech.data.intelligence.common.exception.BizExceptionEnum;
import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.intelligence.common.utils.PageUtils;
import cn.getech.data.intelligence.common.utils.PojoUtils;
import cn.getech.data.intelligence.common.utils.R;
import cn.getech.system.center.annotation.SysLog;
import cn.getech.system.center.constant.OperationModulesEnum;
import cn.getech.system.center.constant.OperationTypeEnum;
import cn.getech.system.center.constant.module.ModuleEnum;
import cn.getech.system.center.entity.SysRoleEntity;
import cn.getech.system.center.service.SysRoleService;
import cn.getech.system.center.utils.ShiroUtils;
import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * <p>
 * 上传版本包记录 前端控制器
 * </p>
 *
 * @author hujz
 * @since 2020-07-03
 */
@Slf4j
@RestController
@RequestMapping("/bdp/uploadVersionLog")
public class UploadVersionLogController {

    @Autowired
    private UploadVersionLogService uploadVersionLogService;
    @Autowired
    private SysRoleService sysRoleService;

    @ApiOperation(value = "分页查询导入版本包列表")
    @PostMapping("/page")
    @SysLog(value="分页查询导入版本包列表",type= OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    //todo 0925
    //@RequiresPermissions({"bdp:procInfo:manage"})
    public R page(@RequestBody UploadVersionLogQO uploadVersionLogQO) {
        PageUtils page = uploadVersionLogService.page(uploadVersionLogQO);
        if (null != page) {
            List<UploadVersionLogVO> bdpVersionVOS = PojoUtils.listConvert(UploadVersionLogVO.class, page.getList());
            //查询到角色信息
            Long userId = ShiroUtils.getUserId();
            List<SysRoleEntity> list = sysRoleService.selectAllGrantRoles(userId);
            if(CollectionUtil.isNotEmpty(list)){
                List<IdAndNameVO> lll = new ArrayList<>();
                for (SysRoleEntity sysRoleEntity : list) {
                    IdAndNameVO idAndNameVO = new IdAndNameVO();
                    idAndNameVO.setId(Integer.valueOf(sysRoleEntity.getRoleId().toString()));
                    idAndNameVO.setName(sysRoleEntity.getRoleName());
                    lll.add(idAndNameVO);
                }
                for (UploadVersionLogVO bdpVersionVO : bdpVersionVOS) {
                    bdpVersionVO.setRoles(lll);
                }
            }
            page.setList(bdpVersionVOS);
            return R.okWithPage(page);
        }
        return R.okWithPage(null);
    }

    @ApiOperation("上传版本包")
    @PostMapping("/uploadVersionZip")
    @SysLog(value="上传版本包",type= OperationTypeEnum.UPLOADCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    //todo 0925
    //@RequiresPermissions({"bdp:procInfo:manage"})
    public R uploadVersionZip(@RequestParam("procId") Integer procId,
                              @RequestParam(value = "zipPathName", required = false) String zipPathName,
                              @RequestParam(value = "file") MultipartFile multipartFile) {
        UploadVersionLogVO uploadVersionLogVO = new UploadVersionLogVO();
        if (multipartFile == null) {
            throw new RRException("未检测到上传的版本包请您重新上传！");
        }
        if (multipartFile.getOriginalFilename() == null) {
            throw new RRException(BizExceptionEnum.MODEL_NAME_IS_NULL);
        }
        if (!multipartFile.getOriginalFilename().endsWith(".zip") && !multipartFile.getOriginalFilename().endsWith(".rar")) {
            throw new RRException("请确定导入的版本包的文件格式！");
        }

        if (!multipartFile.isEmpty()) {
            try {
                //解析jar包类和方法
                UploadVersionLogDto uploadVersionLogDto = uploadVersionLogService.uploadVersionZip(procId, zipPathName, multipartFile);
                if (null != uploadVersionLogDto) {
                    BeanUtils.copyProperties(uploadVersionLogDto, uploadVersionLogVO);
                }
            } catch (Exception e) {
                throw new RRException(e.getMessage());
            }
        } else {
            throw new RRException("您上传的版本包为空！");
        }
        return R.okWithData(uploadVersionLogVO);
    }

    @ApiOperation(value = "轮询状态")
    @PostMapping("/getUploadLog")
    public R getUploadLog(String zipPathName) {
        UploadVersionLogDto uploadVersionLogDto = uploadVersionLogService.getUploadLog(zipPathName);
        if(null != uploadVersionLogDto){
            UploadVersionLogStatusVO uploadVersionLogVO = new UploadVersionLogStatusVO();
            BeanUtils.copyProperties(uploadVersionLogDto,uploadVersionLogVO);
            return R.okWithData(uploadVersionLogVO);
        }
        return R.okWithData(null);
    }

    @ApiOperation(value = "完成")
    @PostMapping("/finsh")
    @SysLog(value="完成",type= OperationTypeEnum.UPDATECODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R finsh(String zipPathName) {
        uploadVersionLogService.finsh(zipPathName);
        return R.okWithData(null);
    }

    @ApiOperation(value = "更新授权的角色信息")
    @PostMapping("/uploadNext")
    @SysLog(value="更新授权的角色信息",type= OperationTypeEnum.UPDATECODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R uploadNext(@RequestBody UploadVersionUpdateRoleVO uploadVersionUpdateRoleVO) {
        uploadVersionLogService.updateRole(uploadVersionUpdateRoleVO);
        return R.okWithData(null);
    }

    @ApiOperation(value = "取消上传")
    @PostMapping("/cancelupload")
    @SysLog(value="取消上传",type= OperationTypeEnum.UPDATECODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R cancelupload(String zipPathName) {
        uploadVersionLogService.cancelupload(zipPathName);
        return R.okWithData(null);
    }

    @ApiOperation(value = "文件检测")
    @PostMapping("/fileCheck")
    @SysLog(value="文件检测",type= OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R fileCheck(String zipPathName) {
        UploadVersionCheckResultLogDto uploadVersionCheckResultLogDto = uploadVersionLogService.fileCheck(zipPathName);
        if(null != uploadVersionCheckResultLogDto){
            UploadVersionCheckResultLogVO uploadVersionCheckResultLogVO = new UploadVersionCheckResultLogVO();
            BeanUtils.copyProperties(uploadVersionCheckResultLogDto,uploadVersionCheckResultLogVO);
            uploadVersionCheckResultLogVO.setAllCheckResults(PojoUtils.listConvert(UploadVersionAllJsonCheackLogVO.class,uploadVersionCheckResultLogDto.getAllCheckResults()));
            return R.okWithData(uploadVersionCheckResultLogVO);
        }
        return R.okWithData(new UploadVersionCheckResultLogVO());
    }

    @ApiOperation(value = "重试检测")
    @PostMapping("/reCheack")
    @SysLog(value="重试检测",type= OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R reCheack(Long cheackLogId) {
        uploadVersionLogService.reCheack(cheackLogId);
        return R.okWithData(null);
    }

    @ApiOperation(value = "获取数据源的导入项和结果")
    @PostMapping("/connectRests")
    public R connectRests(String zipPathName) {
        UploadVersionConnectResultLogSumDto uploadVersionConnectResultLogSumDto = uploadVersionLogService.connectRests(zipPathName);
        if(null != uploadVersionConnectResultLogSumDto){
            UploadVersionConnectResultLogSumVO uploadVersionConnectResultLogSumVO = new UploadVersionConnectResultLogSumVO();
            BeanUtils.copyProperties(uploadVersionConnectResultLogSumDto,uploadVersionConnectResultLogSumVO);
            uploadVersionConnectResultLogSumVO.setAllCheckResults(PojoUtils.listConvert(UploadVersionConnectResultLogVO.class, uploadVersionConnectResultLogSumDto.getAllCheckResults()));
            return R.okWithData(uploadVersionConnectResultLogSumVO);
        }
        return R.okWithData(new UploadVersionConnectResultLogSumVO());
    }

    @ApiOperation(value = "确认导入数据源")
    @PostMapping("/confirmImportConnects")
    @SysLog(value="确认导入数据源",type= OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R confirmImportConnects(String zipPathName) {
        log.info("开始确认导入数据源：zipPathName：{}",zipPathName);
        uploadVersionLogService.confirmImportConnects(zipPathName);
        return R.okWithData(null);
    }

    @ApiOperation(value = "重试数据源导入")
    @PostMapping("/reImportConnect")
    @SysLog(value="重试数据源导入",type= OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R reImportConnect(Long connectLogId) {
        log.info("开始重试导入数据源：connectLogId：{}",connectLogId);
        uploadVersionLogService.reImportConnect(connectLogId);
        return R.okWithData(null);
    }

    @ApiOperation(value = "获取仓库的导入项和结果")
    @PostMapping("/tableRests")
    public R tableRests(String zipPathName) {
        UploadVersionTableResultLogSumDto uploadVersiontableResultLogSumDto = uploadVersionLogService.tableRests(zipPathName);
        if(null != uploadVersiontableResultLogSumDto){
            UploadVersionTableResultLogSumVO uploadVersionTableResultLogSumVO = new UploadVersionTableResultLogSumVO();
            BeanUtils.copyProperties(uploadVersiontableResultLogSumDto,uploadVersionTableResultLogSumVO);
            uploadVersionTableResultLogSumVO.setAllCheckResults(PojoUtils.listConvert(UploadVersionTableResultLogVO.class, uploadVersiontableResultLogSumDto.getAllCheckResults()));
            return R.okWithData(uploadVersionTableResultLogSumVO);
        }
        return R.okWithData(new UploadVersionConnectResultLogSumVO());
    }

    @ApiOperation(value = "确认导入仓库")
    @PostMapping("/confirmImportTables")
    @SysLog(value="确认导入仓库",type= OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R confirmImportTables(String zipPathName) {
        uploadVersionLogService.confirmImportTables(zipPathName);
        return R.okWithData(null);
    }

    @ApiOperation(value = "重试仓库导入")
    @PostMapping("/reImportTable")
    @SysLog(value="重试仓库导入",type= OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R reImportTable(Long tableLogId) {
        uploadVersionLogService.reImportTable(tableLogId);
        return R.okWithData(null);
    }


    @ApiOperation(value = "获取工作流的导入项和结果")
    @PostMapping("/workflowRests")
    public R workflowRests(String zipPathName) {
        UploadVersionWorkFlowResultLogSumDto uploadVersionWorkflowResultLogSumDto = uploadVersionLogService.workflowRests(zipPathName);
        if(null != uploadVersionWorkflowResultLogSumDto){
            UploadVersionWorkFlowResultLogSumVO uploadVersionWorkFlowResultLogSumVO = new UploadVersionWorkFlowResultLogSumVO();
            BeanUtils.copyProperties(uploadVersionWorkflowResultLogSumDto,uploadVersionWorkFlowResultLogSumVO);
            uploadVersionWorkFlowResultLogSumVO.setAllCheckResults(PojoUtils.listConvert(UploadVersionWorkflowResultLogVO.class, uploadVersionWorkflowResultLogSumDto.getAllCheckResults()));
            return R.okWithData(uploadVersionWorkFlowResultLogSumVO);
        }
        return R.okWithData(new UploadVersionConnectResultLogSumVO());
    }

    @ApiOperation(value = "确认导入工作流")
    @PostMapping("/confirmImportWorkflows")
    @SysLog(value="确认导入工作流",type= OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R confirmImportWorkflows(String zipPathName) {
        uploadVersionLogService.confirmImportWorkflows(zipPathName);
        return R.okWithData(null);
    }

    @ApiOperation(value = "重试工作流导入")
    @PostMapping("/reImportWorkflows")
    @SysLog(value="重试工作流导入",type= OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    public R reImportWorkflows(Long workflowLogId) {
        uploadVersionLogService.reImportWorkflows(workflowLogId);
        return R.okWithData(null);
    }

    @ApiOperation("项目回滚")
    @GetMapping("/rollbackProject/{id}")
    @SysLog(value="项目回滚",type= OperationTypeEnum.RUNCODE, modulesType = OperationModulesEnum.BDPMODELCODE,platformModuleType = ModuleEnum.PROJECT_LIST_MODULE_CODE)
    //todo 0925
    //@RequiresPermissions({"bdp:procInfo:manage"})
    public R rollbackProject(@PathVariable("id") Long versionId) {
        //项目回滚
        List<String> rests = uploadVersionLogService.rollbackProject(versionId);
        return R.okWithData(rests);
    }















//    @ApiOperation("检测版本包中出现的问题")
//    @GetMapping("/cheackUploadVersionZip")
//    //todo 0925
//    //@RequiresPermissions({"bdp:procInfo:manage"})
//    public R cheackUploadVersionZip(@RequestParam("versionUUid") String versionUUid) {
//        //检测版本包对应的结果是否满足条件
//        List<VersionStatusResultVO> restList = uploadVersionLogService.cheackUploadVersionZipByVersionUUid(versionUUid);
//        Map<String, Object> mapRest = new HashMap<>();
//        mapRest.put("sumCount", 0);
//        mapRest.put("failCount", 0);
//        mapRest.put("successCount", 0);
//        if (CollectionUtil.isNotEmpty(restList)) {
//            //将列表的工作流名称放入到提示信息中去
//            List<VersionStatusResultVO> copyNameList = new ArrayList<>();
//            for (VersionStatusResultVO data : restList) {
//                List<JSONObject> errorObjLists = data.getErrorObjLists();
//                if(CollectionUtil.isNotEmpty(errorObjLists)){
//                    List<JSONObject> newErrorObjLists = new ArrayList<>();
//                    for (JSONObject errorObjList : errorObjLists) {
//                        Set<String> strings = errorObjList.keySet();
//                        for (String string : strings) {
//                            JSONObject jsonObject = new JSONObject();
//                            jsonObject.put(data.getName(),errorObjList.getString(string));
//                            newErrorObjLists.add(jsonObject);
//                        }
//                    }
//                    data.setErrorObjLists(newErrorObjLists);
//                }
//                copyNameList.add(data);
//            }
//            mapRest.put("restMsgList", copyNameList);
//            mapRest.put("sumCount", restList.size());
//            long successedCount = restList.stream().filter(o -> Objects.equals(o.getErrorNeedType(), 2)).count();
//            mapRest.put("failCount", restList.size() - successedCount);
//            mapRest.put("successCount", successedCount);
//            return R.okWithData(mapRest);
//        }
//        return R.okWithData(mapRest);
//    }
//
//
//    @ApiOperation("确认导入文件")
//    @GetMapping("/importData")
//    //todo 0925
//    //@RequiresPermissions({"bdp:procInfo:manage"})
//    public R importData(@RequestParam("versionUUid") String versionUUid) {
//        //检测版本包对应的结果是否满足条件
//        List<VersionStatusResultVO> restList = uploadVersionLogService.importData(versionUUid);
//        //保存结果记录信息
//        List<UploadVersionResultLogDto> addAllResultList = uploadVersionResultLogService.addList(restList, versionUUid);
//        List<UploadVersionResultLogDto> list = uploadVersionResultLogService.pingRestList(addAllResultList);
//        if (CollectionUtil.isNotEmpty(list)) {
//            List<UploadVersionResultLogVO> rest = new ArrayList<>();
//            for (UploadVersionResultLogDto uploadVersionResultLogDto : list) {
//                UploadVersionResultLogVO uploadVersionResultLogVO = new UploadVersionResultLogVO();
//                BeanUtils.copyProperties(uploadVersionResultLogDto, uploadVersionResultLogVO);
//                if (StringUtils.isNotEmpty(uploadVersionResultLogDto.getRestMsgList())) {
//                    JSONArray jsonArray = JSONArray.parseArray(uploadVersionResultLogDto.getRestMsgList());
//                    if (CollectionUtil.isNotEmpty(jsonArray)) {
//                        uploadVersionResultLogVO.setRestMsgList(jsonArray.toJavaList(JSONObject.class));
//                    }
//                }
//                rest.add(uploadVersionResultLogVO);
//            }
//            return R.okWithData(rest);
//        }
//        return R.okWithData(null);
//    }
//
//
//    @ApiOperation("导入版本包的结果日志查询")
//    @GetMapping("/importResultLog")
//    //todo 0925
//    //@RequiresPermissions({"bdp:procInfo:manage"})
//    public R importResultLog(@RequestParam("id") Long id) {
//        List<UploadVersionResultLogDto> addAllResultList = uploadVersionResultLogService.listByUploadLogId(id);
//        if (CollectionUtil.isNotEmpty(addAllResultList)) {
//            List<UploadVersionResultLogVO> rest = new ArrayList<>();
//            for (UploadVersionResultLogDto uploadVersionResultLogDto : addAllResultList) {
//                UploadVersionResultLogVO uploadVersionResultLogVO = new UploadVersionResultLogVO();
//                BeanUtils.copyProperties(uploadVersionResultLogDto, uploadVersionResultLogVO);
//                if (StringUtils.isNotEmpty(uploadVersionResultLogDto.getRestMsgList())) {
//                    JSONArray jsonArray = JSONArray.parseArray(uploadVersionResultLogDto.getRestMsgList());
//                    if (CollectionUtil.isNotEmpty(jsonArray)) {
//                        uploadVersionResultLogVO.setRestMsgList(jsonArray.toJavaList(JSONObject.class));
//                    }
//                }
//                rest.add(uploadVersionResultLogVO);
//            }
//            return R.okWithData(rest);
//        }
//        return R.okWithData(null);
//    }





}

